package cn.pping.exception;

import cn.pping.result.JSONResult;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description: 全局异常处理类
 * @Author: Pan
 * @Version: 1.0
 * @Date: 2022/8/26 10:26
 */
@RestControllerAdvice
// 日志器注解
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public JSONResult exceptionHandler(Exception e) {
        e.printStackTrace();
        log.error("发生系统异常" + e.getMessage());
        return JSONResult.error(GlobalEnumCode.ERROR);
    }

    @ExceptionHandler(value = GlobalException.class)
    public JSONResult globalException(GlobalException e) {
        e.printStackTrace();
        log.info("发生业务异常，异常码：{}, 异常信息：{}", e.getErrorCode(), e.getErrorMessage());
        return JSONResult.error(e);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        StringBuffer stringBuffer = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(item -> stringBuffer.append(item.getDefaultMessage()).append(";")
        );
        log.error("发生方法参数校验异常，异常信息为：" + e.getMessage());
        return JSONResult.error(stringBuffer.toString());
    }

}
